package com.zp95sky.demo.aidemo.common.exception.handler;

import com.zp95sky.demo.aidemo.common.constant.ResponseCodeConstant;
import com.zp95sky.demo.aidemo.common.exception.CustomException;
import com.zp95sky.demo.aidemo.common.response.BaseErrorResponse;
import com.zp95sky.demo.aidemo.common.utils.ResponseUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理
 */
@ControllerAdvice
@Slf4j
@RequiredArgsConstructor
public class CommonExceptionHandler {

    private final ResponseUtil responseUtil;

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public BaseErrorResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("method argument not valid exception: ", ex);
        return responseUtil.buildErrorResponse(ResponseCodeConstant.BAD_REQUEST_CODE);
    }

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseBody
    public BaseErrorResponse handleIllegalArgumentException(Exception ex) {
        log.error("illegal argument exception: ", ex);
        return responseUtil.buildErrorResponse(ResponseCodeConstant.BAD_REQUEST_CODE);
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    private BaseErrorResponse handleCustomException(CustomException exception) {
        log.error("custom exception: ", exception);
        return responseUtil.buildErrorResponse(exception.getCode());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseErrorResponse resolveException(Exception e) {
        log.error("exception: ", e);
        return responseUtil.buildErrorResponse(ResponseCodeConstant.INTERNAL_SERVER_ERROR_CODE);
    }

}
